﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("异步:");
            DisplayPrimeLongtimeCountsAsync();
            //DisplayPrimeLongtimeCounts();
            //Console.WriteLine("同步:");
            //DisplayPrimeLongtimeCounts(0);
            Console.ReadLine();
        }

        async static void DisplayPrimeLongtimeCountsAsync() 
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Count:{0} , Value:{1}", i, await GetLongtimeCounts(i));
            }
            Console.WriteLine("Over");
        }
        static void DisplayPrimeLongtimeCounts() 
        {
            for (int i = 0; i < 10; i++)
            {
                var temp = i;
                var awaits = GetLongtimeCounts(temp).GetAwaiter();
                awaits.OnCompleted(() =>
                {
                    Console.WriteLine("Count:{0} , Value:{1}", temp, awaits.GetResult());
                });
            }
            Console.WriteLine("Over");
        }
        static void DisplayPrimeLongtimeCounts(int i)
        {
            var awaits = GetLongtimeCounts(i).GetAwaiter();
            var temp = i;
            awaits.OnCompleted(() =>
            {
                if (++temp <= 10)
                {
                    Console.WriteLine("Count:{0} , Value:{1}", i, awaits.GetResult());
                    DisplayPrimeLongtimeCounts(temp);
                }
                else
                {
                    Console.WriteLine("Over");
                }
            });
        }
        static Task<int> GetLongtimeCounts(int i)
        {
            return Task.Run(() =>
            {
                Random rdm = new Random();
                var time = rdm.Next(800, 1000);
                Thread.Sleep(time);
                return i * time;
            });
        }
    }
}
